import * as vscode from 'vscode';
import * as fs from 'fs';
import * as path from 'path';
import { request } from 'http';

//class OllamaChatProvider implements vscode.WebviewViewProvider {
//  public webviewView?: vscode.WebviewView;

class HelloWorldPanel {
  public static currentPanel: HelloWorldPanel | undefined;
  private readonly _panel: vscode.WebviewPanel;
  private readonly _extensionUri: vscode.Uri;
  private _disposables: vscode.Disposable[] = [];

  constructor(panel: vscode.WebviewPanel, extensionUri: vscode.Uri) {
    this._panel = panel;
    this._extensionUri = extensionUri;
    this._panel.onDidDispose(() => this.dispose(), null, this._disposables);
    this._panel.webview.html = this._getWebviewContent(this._panel.webview, this._extensionUri);

    // **关键修复**: 为 WebviewPanel 添加消息监听器
    this._panel.webview.onDidReceiveMessage(
      async message => {
        if (message.command === 'sendPrompt') {
          // 调用新的流式 Ollama 响应函数
          streamOllamaResponse(message.messages, this._panel.webview);
        }
      },
      undefined,
      this._disposables
    );

  }

  public static render(extensionUri: vscode.Uri) {
    if (HelloWorldPanel.currentPanel) {
      HelloWorldPanel.currentPanel._panel.reveal(vscode.ViewColumn.Beside);
    } else {
      const panel = vscode.window.createWebviewPanel(
        'intdosCodeMate', // **关键修复**: 使用新的视图类型 ID
        'INTDOS-CodeMate', // 标题
        vscode.ViewColumn.Beside, // 显示位置
        {
          enableScripts: true,
          localResourceRoots: [vscode.Uri.joinPath(extensionUri, 'dist')]
        }
      );

      HelloWorldPanel.currentPanel = new HelloWorldPanel(panel, extensionUri);
    }
  }




  private _getWebviewContent(webview: vscode.Webview, extensionUri: vscode.Uri) {
    // 1. 获取编译后的 webview UI (React) 的 JavaScript 文件 URI
    const scriptUri = webview.asWebviewUri(vscode.Uri.joinPath(
        extensionUri, 'dist', 'webview.js'
    ));

    // 2. 读取我们的 index.html 模板
    const templateHtmlPath = path.join(extensionUri.fsPath, 'src', 'webview-ui', 'index.html');
    let templateHtml = fs.readFileSync(templateHtmlPath, 'utf-8');

    // 3. 将编译后的脚本路径注入到 HTML 模板中
    templateHtml = templateHtml.replace(
        '<script type="module" src="/index.tsx"></script>',
        `<script type="module" src="${scriptUri}"></script>`
    );

    return templateHtml;
  }

  public dispose() {
    HelloWorldPanel.currentPanel = undefined;
    this._panel.dispose();
    while (this._disposables.length) {
      const disposable = this._disposables.pop();
      if (disposable) {
        disposable.dispose();
      }
    }
  }
}


export function activate(context: vscode.ExtensionContext) {
  // **关键修复**: 注册正确的命令 ID
  const helloWorldCommand = vscode.commands.registerCommand('intdos.codeMate', () => {
    HelloWorldPanel.render(context.extensionUri);
  });
  context.subscriptions.push(helloWorldCommand);
}

// **关键修复**: 使用新的流式 Ollama 响应函数
function streamOllamaResponse(messages: any[], webview: vscode.Webview) {
  const req = request(
    {
      hostname: "localhost",
      port: 1234, // 确保端口与你的 Ollama 服务一致
      path: "/v1/chat/completions",
      method: "POST",
      headers: { "Content-Type": "application/json" },
    },
    (res) => {
      res.on("data", (chunk) => {
        const chunkStr = chunk.toString();
        // Ollama 的流式 API 可能会在一个 chunk 中发送多行
        const lines = chunkStr.split("\n").filter((line: string) => line.trim() !== "");
        for (const line of lines) {
          if (line.startsWith("data: ")) {
            const jsonData = line.substring(6);
            if (jsonData.trim() === "[DONE]") {
              webview.postMessage({ command: "responseFinished" });
              return;
            }
            try {
              const parsed = JSON.parse(jsonData);
              if (parsed.choices && parsed.choices[0] && parsed.choices[0].delta) {
                const content = parsed.choices[0].delta.content;
                if (content) {
                  webview.postMessage({ command: "receiveResponseChunk", text: content });
                }
              }
            } catch (e) {
              console.error("Error parsing Ollama stream chunk:", e, "Chunk:", jsonData);
            }
          }
        }
      });
      res.on("end", () => {
        webview.postMessage({ command: "responseFinished" });
      });
      res.on("error", (e) => {
        console.error("Error from Ollama stream:", e);
        webview.postMessage({ command: "responseError", error: e.message });
      });
    }
  );
  req.on("error", (e) => {
    console.error("Error making request to Ollama:", e);
    webview.postMessage({ command: "responseError", error: "Failed to connect to Ollama. Make sure it is running on http://localhost:1234." });
  });
  const body = {
    model: "google/gemma-3-4b", // 确保你本地有这个模型
    messages,
    stream: true,
  };
  req.write(JSON.stringify(body));
  req.end();
}


export function deactivate() {}